package utils

import (
	"fmt"
	"gopkg.in/gomail.v2"
	"gvb-server/global"
	"math/rand"
	"time"
)

type Subject string

const (
	Code  Subject = "平台验证码"
	Note  Subject = "平台通知"
	Alarm Subject = "普通通知"
)

type Api struct {
	Subject Subject
}

func (a Api) Send(name, body string) error {
	return send(name, string(a.Subject), body)
}

// NewCode 直接使用此方法 调用send即可例如：NewCode.Send(发给谁，内容)
func NewCode() Api {
	return Api{Subject: Code}
}
func NewNote() Api {
	return Api{Subject: Note}
}
func NewAlarm() Api {
	return Api{Subject: Alarm}
}

func send(name, subject, body string) error {
	e := global.Config.Email
	return sendEmail(e.User, e.PassWord, e.Host, e.Prod, name, e.DefaultFromEmail, subject, body)
}

func sendEmail(userName, authCode, host string, prod int, mailTo, sendName string, subject, body string) error {

	m := gomail.NewMessage()
	m.SetHeader("From", m.FormatAddress(userName, sendName)) // 发件人邮箱 发件人名称
	m.SetHeader("To", mailTo)                                //发给谁
	m.SetHeader("Subject", subject)                          //主题
	m.SetBody("text/html", body)
	d := gomail.NewDialer(host, prod, userName, authCode)

	err := d.DialAndSend(m)
	return err
}

// RandCode 4位验证码
func RandCode() string {
	rand.Seed(time.Now().UnixNano())
	return fmt.Sprintf("%4v", rand.Intn(10000))
}
